import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { mallApi } from '/api/mall'

Page({
  data: {
    isFullScreen: false,
    navigationHeight: GlobalData.navigationHeight,
    company: '',
    companyTips: '请选择物流公司',
    canSubmit: false,
    ids: [],
    companyId: 0,
    expressId: 0,
    edit: false,
    id: '',
    buyer: false, // 是否是买家
    orderList: [] as any,
  },
  onLoad(query?: any) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      buyer: !!query.buyer,
    })
    if (query.id) {
      this.setData({
        expressId: query.id,
        company: query.company,
        companyId: query.companyId,
        edit: true,
        id: query.number,
      })
    }
  },
  onShow() {
    if (this.data.ids.length > 0 || (this.data.id && this.data.company)) {
      this.setData({
        canSubmit: true,
      })
    }
    $event.on('after:boot', this, () => {
      this.setData({ navigationHeight: GlobalData.navigationHeight })
    })
    this.setData({ navigationHeight: GlobalData.navigationHeight })
    if (GlobalData.shipInfo.orderIds.length) {
      const pages = getCurrentPages()
      const orderInfo = pages[pages.length - 2].data.orderInfo
      const orderList = [] as any
      orderInfo.sub_orders.forEach((order: any) => {
        if (GlobalData.shipInfo.orderIds.includes(order.id)) {
          orderList.push(order)
        }
      })
      this.setData({
        orderList,
      })
    } else if (GlobalData.shipInfo.orderId) {
      const pages = getCurrentPages()
      const orderInfo = pages[pages.length - 2].data.orderInfo
      const orderList = [] as any
      orderList.push(orderInfo)
      this.setData({
        orderList,
      })
    }
  },
  onInoput(e: WechatMiniprogram.CustomEvent) {
    const ids = e.detail.value.split(/[^a-z\d]/i).filter(Boolean)
    if (ids.length > 0 && this.data.company) {
      this.setData({
        canSubmit: true,
      })
    } else {
      this.setData({
        canSubmit: false,
      })
    }
    this.setData({
      ids,
    })
  },
  editInoput(e: WechatMiniprogram.CustomEvent) {
    const id = e.detail.value.replace(/[^a-z\d]/gi, '')
    if (id && this.data.company) {
      this.setData({
        canSubmit: true,
      })
    } else {
      this.setData({
        canSubmit: false,
      })
    }
    this.setData({
      id,
    })
  },
  chooseCompany() {
    wx.navigateTo({
      url: '/mall/fillShipInfo/chooseCompany/chooseCompany',
    })
  },
  async onSubmit() {
    if (!this.data.canSubmit) return
    if (this.data.edit) {
      if (this.data.buyer) {
        // 买家
        const data = {
          refund_id: GlobalData.shipInfo.retId,
          company_id: this.data.companyId,
          number: this.data.id,
        }
        await mallApi.putExpresses(GlobalData.shipInfo.retId, data)
      } else {
        // 商家
        const data = {
          company_id: this.data.companyId,
          number: this.data.id,
        } as ResetExpressesParam
        await mallApi.resetExpresses(this.data.expressId, data)
      }
    } else {
      // 聚合订单发货
      const ids: Array<any> = this.data.buyer
        ? [GlobalData.shipInfo.retId]
        : GlobalData.shipInfo.orderIds.length
          ? GlobalData.shipInfo.orderIds
          : [GlobalData.shipInfo.orderId]
      await Promise.all(
        ids.map((id: any) => {
          if (this.data.buyer) {
            // 买家
            const data = {
              refund_id: id,
              company_id: this.data.companyId,
              number: this.data.id,
            }
            return mallApi.postExpresses(data)
          } else {
            // 商家
            const data = {
              order_id: id,
              company_id: this.data.companyId,
              numbers: this.data.ids,
            }
            return mallApi.addOrderExpresses(data)
          }
        }),
      )

      // 重置
      GlobalData.shipInfo.retId = 0
      GlobalData.shipInfo.orderId = 0
      GlobalData.shipInfo.orderIds = []

      $event.emit('mallOrderChange')
      wx.showToast({
        title: '添加成功',
      })
    }
    setTimeout(() => {
      wx.navigateBack({
        delta: this.data.buyer ? 2 : 1,
      })
    }, 1000)
  },
})
